<script lang="ts" setup>
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import {computed, onBeforeUnmount, ref, shallowRef} from "vue";
import {FileBo, FileVo} from "@/dto/file/File.ts";
import Result from "@/common/Result.ts";
import '@wangeditor/editor/dist/css/style.css' // 引入 css

const editorRef = shallowRef()
const mode = "default"
const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {}
}
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const props = defineProps({
    modelValue: {
        type: String,
        default: ""
    },
    height:{
        type:Number,
        default:500
    }
})

const emit = defineEmits(["update:modelValue"])

const valueHtml = computed({
    get() {
        return props.modelValue
    }, set(value) {
        emit("update:modelValue", value)
    }
})


onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

type InsertFnType = (url: string, alt: string, href: string) => void

function getFileBo() {
    let bo = new FileBo(
        new Date().toString(),
        "jpg",
        ".jpg",
        new Date().toString(),
        1
    );
    bo.number = 1;
    return bo
}

editorConfig.MENU_CONF['uploadImage'] = {
    fieldName: 'file',
    server: `${import.meta.env.VITE_BACKEND_SERVER_URL}/api/file/editor_upload`,
    allowedFileTypes: [],
    // 上传图片的自定义参数
    maxFileSize: 10 * 1024 * 1024, // 10M
    maxNumberOfFiles: 10,
    meta: {
        fileBo: getFileBo()
    },
    async customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
        // res 即服务端的返回结果
        let urls = FileVo.getUploadUrl(String(res.data.url));
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(urls, <string>res.data?.fileName, urls)
    },
}
</script>

<template>

    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        :style="'height:'+props.height+'px; overflow-y: hidden;'"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
    />
</template>

<style scoped>

</style>